local zhiji = fk.CreateSkill {
  name = "ls__zhiji",
}

Fk:loadTranslationTable{
  ["ls__zhiji"] = "知机",
  [":ls__zhiji"] = "轮次开始时，你可声明一个花色。此轮该花色的牌被首次使用时，你卜算X并分配其中最多三张牌。X为此轮进行的回合数+1。",
  ["#ls__zhiji-choose"] = "知机：请选择一个花色",
  ["#ls__zhiji-busuan"] = "知机：分配至多三张牌",
  ["@zhiji_suit-round"] = "知机",
  ["@@zhiji_triggered-round"] = "知机<font color='red'><b>已发动</b></font>",
  
  ["$ls__zhiji1"] = "事已至此，顺应天意吧。",
  ["$ls__zhiji2"] = "各由天命，何不泰然处之。",
}

-- 轮次开始时选择花色
zhiji:addEffect(fk.RoundStart, {
  anim_type = "special",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(zhiji.name)
  end,
  on_cost = function(self, event, target, player, data)
    local choice = player.room:askToChoice(player, {
      choices = {"log_spade", "log_heart", "log_club", "log_diamond"},
      skill_name = zhiji.name,
      prompt = "#ls__zhiji-choose",
    })
    if choice then
      event:setCostData(self, {suit = choice})
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local suit = event:getCostData(self).suit
    player.room:setPlayerMark(player, "@zhiji_suit-round", {suit})
  end,
})

-- 花色牌首次使用时触发卜算
zhiji:addEffect(fk.CardUsing, {
  anim_type = "drawcard",
  is_delay_effect = true,
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(zhiji.name) or player:getMark("@zhiji_suit-round") == 0 then return end
    if player:getMark("@@zhiji_triggered-round") > 0 then return end
    return data.card:getSuitString(true) == player:getMark("@zhiji_suit-round")[1]
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:setPlayerMark(player, "@zhiji_suit-round", 0)
    room:addPlayerMark(player, "@@zhiji_triggered-round")
    -- 计算X值（本轮已进行的回合数+1）
    local turns_in_round = #player.room.logic:getEventsOfScope(GameEvent.Turn, 1, function(e)
      return true  -- 统计本轮所有玩家的回合
    end, Player.HistoryRound)
    local x = turns_in_round + 1 + player:getMark("@ls__qizuo_guanxing")--耦
    -- 卜算X张牌（观星牌堆顶的X张牌）
    local guanxing_cards = room:getNCards(x)
    if #guanxing_cards == 0 then return end
    
    -- 使用askToYiji分配至多三张牌
    local distribution_result = room:askToYiji(player, {
      cards = guanxing_cards,
      min_num = 1,
      max_num = math.min(3, #guanxing_cards),
      skill_name = zhiji.name,
      prompt = "#ls__zhiji-busuan",
      expand_pile = guanxing_cards,
    })
    
    -- 从观星牌中移除已分配的牌
    if distribution_result then
      for _, target_cards in pairs(distribution_result) do
        for _, card_id in ipairs(target_cards) do
          table.removeOne(guanxing_cards, card_id)
        end
      end
    end
    
    -- 将其余牌进行观星（让玩家决定顺序）
    if #guanxing_cards > 0 then
      room:askToGuanxing(player, {
        cards = guanxing_cards,
        skill_name = zhiji.name,
        prompt = "知机：将剩余的牌放回牌堆",
      })
    end
  end,
})

return zhiji